﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace IntegratedOnBordDebug.UDPCore
{
    /// <summary>
    /// Encapsulates a collection of SocketAsyncEventArgs that can be reused
    /// </summary>
    public class SAEAPool
    {
        public List<ObjectDTU> Pools = new List<ObjectDTU>();

        /// <summary>
        /// Contains all the SocketAsyncEventArgs that aren't being used by any
        /// AsyncClient instance
        /// </summary>
        ConcurrentQueue<SocketAsyncEventArgs> _socketAsyncEventArgsQueue;

        /// <summary>
        /// Encapsulates a collection of SocketAsyncEventArgs that can be reused
        /// </summary>
        public SAEAPool()
        {
            _socketAsyncEventArgsQueue = new ConcurrentQueue<SocketAsyncEventArgs>();
        }

        /// <summary>
        /// Try to gets a non used SocketAsyncEventArgs from the pool
        /// </summary>
        /// <param name="e">Reference that will hold the non used
        /// SocketAsyncEventArgs instance</param>
        /// <returns>Returns True if the operation was completed succesfully,
        /// False otherwise</returns>
        public bool TryPop(out SocketAsyncEventArgs e)
        {
            return _socketAsyncEventArgsQueue.TryDequeue(out e);
        }

        /// <summary>
        /// Adds a SocketAsyncEventArgs instance that is not being used 
        /// to the pool
        /// </summary>
        /// <param name="e">SocketAsyncEventArgs that will be added to the pool</param>
        public void Push(SocketAsyncEventArgs e)
        {
            _socketAsyncEventArgsQueue.Enqueue(e);
        }
    }
}
